package com.wealth.cart.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wealth.cart.entity.Cart;
import com.wealth.cart.entity.CartGoodsInfo;
import com.wealth.cart.entity.CartItem;
import com.wealth.cart.enums.CartStatusEnum;
import com.wealth.cart.repository.CartDao;
import com.wealth.cart.repository.CartItemDao;
import com.wealth.cart.service.ICartItemService;
import com.wealth.cart.service.ICartService;
import com.wealth.commodity.entity.Goods;
import com.wealth.member.entity.Member;
import com.wealth.merchant.entity.Market;
import com.wealth.merchant.entity.Merchant;
import com.wealth.merchant.repository.ActivityDao;
import com.wealth.merchant.repository.MerchantDao;

import iaas.enums.StatusEnum;
import iaas.service.impl.BaseServiceImpl;

@Component
public class CartServiceImpl  extends BaseServiceImpl<Cart> implements ICartService {

	
    @Autowired
	CartItemDao cartItemDao;
    
    @Autowired
    CartDao cartDao;
    
    @Autowired
    ICartItemService icartItemService;
    
    @Autowired
    MerchantDao merchantDao;
    @Autowired
    ActivityDao activityDao;
    
    
    private static double  toDouble(double total){
    	return Double.parseDouble(new DecimalFormat("#.00").format(total));
    }
	
	@Override
	public void addCart(long memberid,int amount, Goods goods,Long marketId) throws Exception {
		 
		Cart cartInfo = cartDao.findCartByMemberIdAndMarketId(memberid, marketId);
		CartItem cartItem = new CartItem();
		//保存购物车
		if(cartInfo==null){
			Cart cart = new Cart();
			cart.setMember(new Member(memberid));
			cart.setTotal(goods.getPrice());
			cart.setAmount(amount);
			cart.setCreatetime(new Date());   
			cart.setMarket(new Market(marketId));
			 save(cart); 
			 cartItem.setCart(cart);//对应购物车
		 }else{
			 cartItem.setCart(cartInfo);//对应购物车
		 }
		
		 //保存购物车商品 
		 CartItem cartItemInfo = cartItemDao.findCartItemByGoodsIdAndCartId(goods.getId(), cartItem.getCart().getId());
		
		  if(cartItemInfo==null){ //购物车没商品
			cartItem.setGoods(goods);
			cartItem.setPrice(goods.getPrice());
			cartItem.setAmount(amount);
			cartItem.setCreatetime(new Date());
			cartItem.setStatus(CartStatusEnum.SELECT.getValue());
			cartItem.setMerchant(new Merchant(goods.getMerchant().getId()));
			cartItemDao.save(cartItem); 
			//更新购物车状态
			if(cartInfo!=null){
				cartInfo.setTotal(cartInfo.getTotal()+goods.getPrice());
				cartInfo.setAmount(cartInfo.getAmount()+amount);
				cartDao.save(cartInfo);
			}
			
		  }else{//购物车有商品
			  
			  cartItemInfo.setAmount(cartItemInfo.getAmount()+amount);
			  cartItemDao.save(cartItemInfo);
			//更新购物车状态
			if(cartInfo!=null){
				cartInfo.setAmount(cartInfo.getAmount()+amount);
				cartInfo.setTotal(cartInfo.getTotal()+goods.getPrice());
				cartDao.save(cartInfo);
			}
		  }
	}

	@Override
	public Cart findCartByMemberId(long id) throws Exception {
		 
		return cartDao.findCartByMemberId(id);
	}

	@Override
	public List<CartGoodsInfo> getCartGoodsByMemberId(long memberId,Long marketId)throws Exception {
		
	    List<CartGoodsInfo> cartGoodsInfos = new ArrayList<CartGoodsInfo>();
		
		Cart cart = cartDao.findCartByMemberIdAndMarketId(memberId, marketId);
		if(cart!=null){
			//对应几个商户
			List<CartItem> merchantList = icartItemService.getCartByCartId(cart.getId());
			for (int i = 0; i < merchantList.size(); i++) {
				
				//组装商户
				CartGoodsInfo cartGoodsInfo = new CartGoodsInfo(); 
				cartGoodsInfo.setMerchant(merchantDao.getOne(merchantList.get(i).getMerchant().getId()));
				//获取商户活动
				if(activityDao.findByStatusAndMerchantId(StatusEnum.NORMAL.getValue(), merchantList.get(i).getMerchant().getId()).size()>0){
					cartGoodsInfo.setActivity(activityDao.findByStatusAndMerchantId(StatusEnum.NORMAL.getValue(), merchantList.get(i).getMerchant().getId()).get(0));
				}
				
				//组装对应的商品 
				List<CartItem> cartItems = cartItemDao.findCartItemByCartIdAndMerchantIdAndStatus(merchantList.get(i).getMerchant().getId(),cart.getId(),CartStatusEnum.del.getValue());
				cartGoodsInfo.setList(cartItems);
				for (int j = 0; j < cartItems.size(); j++) {
						 //统计选中的商品
					    if(cartItems.get(j).getStatus()==CartStatusEnum.SELECT.getValue()){
							cartGoodsInfo.setTotalAmount(cartGoodsInfo.getTotalAmount()+cartItems.get(j).getAmount());
							cartGoodsInfo.setTotalPrice(cartGoodsInfo.getTotalPrice()+(cartItems.get(j).getGoods().getPrice()*cartItems.get(j).getAmount()));
						}
				} 
				
				
				cartGoodsInfos.add(cartGoodsInfo);
			} 
		}
		return cartGoodsInfos;
	}

	//修改购物车
	@Override
	public Map<String, Object> saveOrUpdate(Long goodsId, int amount,Long memberid,Long marketId) throws Exception {
		
		Map<String, Object> map=new HashMap<String, Object>();
	
		//获取购物车
		Cart cart = cartDao.findCartByMemberIdAndMarketId(memberid, marketId);
		
		Integer  cartAmount=0;
		//遍历购物车明细
		for (CartItem item  : cart.getCartItems()) {
			if(item.getGoods().getId().equals(goodsId)){
					int disAmount=0;
					if(item.getAmount()>amount){//减
						
						disAmount=item.getAmount()-amount; //相差数量
						cartAmount=cart.getAmount()-disAmount;
					}else if(item.getAmount()<amount){//加
						
						disAmount=amount-item.getAmount(); //相差数量
						cartAmount=cart.getAmount()+disAmount;
					}
					if(amount>0){
						//明细表中商品数量修改
						item.setAmount(amount);
						cartItemDao.save(item); 
					}else if(amount==0){
						cartItemDao.delete(item);
					}
				//计算某商户选中商品的总价格
				map.put("MerchantPrice",toDouble(getMerchantPrice(item.getGoods().getMerchant().getId(), cart)));
			}
		}
		cart.setAmount(cartAmount);
		cart.setTotal(getTotal(cart));
		cartDao.save(cart);
		
		map.put("cartPrice",getTotal(cart));
		
		
		return map;
	}
		
		

	//选中购物车里面的商品
	@Override
	public Map<String, Object> checkCartItem(Long goodsId,Integer status,Long memberid,Long marketId,int amount) throws Exception {
		
		Map<String, Object> map=new HashMap<String, Object>();
		
		//获取购物车
		Cart cart = cartDao.findCartByMemberIdAndMarketId(memberid, marketId);
		Double  carttotal = 0.0;		//金额
		Integer cartamount = 0;		//数量
		//遍历购物车明细
		for (CartItem item  : cart.getCartItems()) {
			if(item.getGoods().getId().equals(goodsId)){
				if(status==CartStatusEnum.NORMAL.getValue()){//取消选中
					item.setStatus(1);
					
				}else if(status==CartStatusEnum.SELECT.getValue()){//选中
					item.setStatus(2);
					item.setAmount(amount);
				}
				cartItemDao.save(item);
				//计算某商户选中商品的总价格
				map.put("MerchantPrice",toDouble( getMerchantPrice(item.getGoods().getMerchant().getId(), cart)));
			}
		}
		//当前所有选中状态的商品
		for (CartItem item  : cart.getCartItems()) {
			if(item.getStatus()==CartStatusEnum.SELECT.getValue()){//如果是选中状态
				carttotal+=item.getPrice()*item.getAmount();
				cartamount+=item.getAmount();
			}
		}
		cart.setAmount(cartamount);
		cart.setTotal(getTotal(cart));
		map.put("cartPrice", getTotal(cart));
		
		cartDao.save(cart);
		
		return map;
	}

		//选中购物车
		@Override
		public Map<String, Object> checkCart(Integer status,Long memberid,Long marketId) throws Exception {
			
			Map<String, Object> map=new HashMap<String, Object>();
			//获取购物车
			Cart cart = cartDao.findCartByMemberIdAndMarketId(memberid, marketId);
			Double total = 0.0;		//金额
			Integer amount = 0;		//数量
			//遍历购物车明细
			for (CartItem item  : cart.getCartItems()) {
				if(status==1){//取消选中
					item.setStatus(1);//选中状态
				}else{//全部选中
					item.setStatus(2);//选中状态
					total+=item.getPrice()*item.getAmount();
					amount+=item.getAmount();
				}
				
				cartItemDao.save(item);
			}
			
			cart.setAmount(amount);
			cart.setTotal(getTotal(cart));	
			cartDao.save(cart);
			map.put("cartPrice",getTotal(cart));
			return map;
		}

		
		
		//会员+市场
		@Override
		public Cart findCartByMemeberIdAndMarketId(Long memberId, Long marketId) {
			return cartDao.findCartByMemberIdAndMarketId(memberId, marketId);
		}
		
		
		//查询购物车
		public Cart findCartByMemberIdAndMarketId(Long memberId,Long marketId){
			return cartDao.findCartByMemberIdAndMarketId(memberId, marketId);
		}
		
		//计算某一商户 选中状态的商品总价
		private  double getMerchantPrice(Long MerchantId,Cart cart){
			double MerchantPrice=0.0;
			for (CartItem cartitem : cart.getCartItems()) {
				//同一商户
				if(cartitem.getGoods().getMerchant().getId().equals(MerchantId)){
					//状态为选中状态
					if(cartitem.getStatus()==CartStatusEnum.SELECT.getValue()){
						MerchantPrice+=cartitem.getAmount() * cartitem.getGoods().getPrice();
					}
				}
			}
			return MerchantPrice;
		}

		@Override
		public void delCart(Cart cart) throws Exception {
				
		}

		//删除购物车明细
		@Override
		public Map<String, Object> delCartItem(Long goodsId,Long memberid,Long marketId) {
			
			Map<String, Object> map=new HashMap<String, Object>();
			//获取购物车
			Cart cart = cartDao.findCartByMemberIdAndMarketId(memberid, marketId);
			for (CartItem cartItem : cart.getCartItems()) {
				if(cartItem.getGoods().getId().equals(goodsId)){
					cartItemDao.delete(cartItem);
				}
			}
			
			map.put("cartPrice", getTotal(cart));
			return map;
			
		}


		//计算购物车总价
		@Override
		public double getTotal(Cart cart) {
			double  total =0.0;
			for (CartItem  cartitem : cart.getCartItems()) {
				if(cartitem.getStatus()==2){
					total+=cartitem.getGoods().getPrice() * cartitem.getAmount();
				}
			}
			return toDouble(total);
		}

		@Override
		public List<CartGoodsInfo> getCheckedCar(long memberId, Long marketId)
				throws Exception {
			List<CartGoodsInfo> cartGoodsInfos = new ArrayList<CartGoodsInfo>();
			
			Cart cart = cartDao.findCartByMemberIdAndMarketId(memberId, marketId);
			if(cart!=null){
				//对应几个商户
				List<CartItem> merchantList = icartItemService.getCheckCarItem(cart.getId());
				for (int i = 0; i < merchantList.size(); i++) {
					
					//组装商户
					CartGoodsInfo cartGoodsInfo = new CartGoodsInfo(); 
					cartGoodsInfo.setMerchant(merchantDao.getOne(merchantList.get(i).getMerchant().getId()));
					//获取商户活动
					if(activityDao.findByStatusAndMerchantId(StatusEnum.NORMAL.getValue(), merchantList.get(i).getMerchant().getId()).size()>0){
						cartGoodsInfo.setActivity(activityDao.findByStatusAndMerchantId(StatusEnum.NORMAL.getValue(), merchantList.get(i).getMerchant().getId()).get(0));
					}
					
					//组装对应的商品 
					List<CartItem> cartItems = cartItemDao.getSelectCartItem(merchantList.get(i).getMerchant().getId(),cart.getId(),CartStatusEnum.SELECT.getValue());
					cartGoodsInfo.setList(cartItems);
					for (int j = 0; j < cartItems.size(); j++) {
							 //统计选中的商品
						    if(cartItems.get(j).getStatus()==CartStatusEnum.SELECT.getValue()){
								cartGoodsInfo.setTotalAmount(cartGoodsInfo.getTotalAmount()+cartItems.get(j).getAmount());
								cartGoodsInfo.setTotalPrice(cartGoodsInfo.getTotalPrice()+(cartItems.get(j).getGoods().getPrice()*cartItems.get(j).getAmount()));
							}
					} 
					cartGoodsInfos.add(cartGoodsInfo);
				} 
			}
			return cartGoodsInfos;
		}
		
		
		
		
		
}
